//
//  ZZPayView.m
//  QQplayground
//
//  Created by zhangxy on 2018/8/16.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "ZZPayView.h"

#import "MyButton.h"

#import "UIView+Border.h"

#import "ZTextView.h"

#import "ZZPayTypeView.h"
#import "PayInfoEntity.h"

#define CHeight 282

#define CWidth SCREEN_WIDTH - 100


@interface ZZPayView()<UITextViewDelegate>{
    MyButton *checkBtn;
}

@property(nonatomic,strong) UIViewController *curVC;

@property(nonatomic,strong) UIView *bottomView;
@property(nonatomic,strong) UIScrollView *itemScroll;
@property(nonatomic,strong) UILabel *labPrice;

@property(nonatomic,strong) PayInfoEntity *payInfo;
@property (nonatomic, copy) void(^VipPayResult)(int code,NSDictionary *message);

@end


@implementation ZZPayView

-(instancetype)initWithShareType:(UIViewController *)vc result:(void (^)(int, NSDictionary *))payResult{
    self = [super initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT)];
    if (self)
    {
        _VipPayResult = payResult;
        _curVC = vc;
        self.backgroundColor = [UIColor clearColor];
        
        [[UIApplication sharedApplication].keyWindow addSubview:self];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dissmisMenu)];
        [self addGestureRecognizer:tap];
        
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(50, SCREEN_HEIGHT-CHeight, CWidth, CHeight)];
        _bottomView.backgroundColor = UIColor.whiteColor;
        _bottomView.layer.cornerRadius = 5.0f;
        _bottomView.layer.masksToBounds = YES;
        [self addSubview:_bottomView];
        
        UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dissmisMenu)];
        [_bottomView addGestureRecognizer:tap1];
        
        [self createInitView];
        
        [self loadVipList];
        
    }
    
    return self;
}
-(void)createInitView{
    UILabel *labTitle = [UILabel new];
    [labTitle setFrame:CGRectMake(15, 17, CWidth - 30, 21)];
    [labTitle setFont:FontFiftent];
    [labTitle setTextAlignment:NSTextAlignmentCenter];
    [labTitle setTextColor:UIColorFromRGB(TextSizeOneColor)];
    [labTitle setText:@"Q友乐园会员"];
    [_bottomView addSubview:labTitle];
    
    UIImageView *imgAvatar = [[UIImageView  alloc] initWithFrame:CGRectMake(100, 55, 33, 33)];
    [imgAvatar setBackgroundColor:UIColor.whiteColor];
    imgAvatar.layer.cornerRadius = 16.5f;
    imgAvatar.layer.masksToBounds = YES;
    [imgAvatar sd_setImageWithURL:[NSURL URLWithString:convertToString([UserUtil getUser].user_avatar)] placeholderImage:[UIImage imageNamed:@"default_image"]];
    [_bottomView addSubview:imgAvatar];
    
    
    UILabel *labName = [[UILabel alloc] initWithFrame:CGRectMake(143, 61, CWidth - 115 - 45, 24)];
    [labName setFont:FontSeventeen];
    [labName setText:[UserUtil getUser].user_name];
    [labName setTextColor:UIColorFromRGB(0x262626)];
    [_bottomView addSubview:labName];
    
    [self autoWidthOfLabel:labName with:24];
    CGRect f = labName.frame;
    [imgAvatar setFrame:CGRectMake( (CWidth - 33 - f.size.width - 5)/2, 55, 33, 33)];
    f.origin.x = CGRectGetMaxX(imgAvatar.frame) + 5;
    labName.frame = f;
    
    _itemScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(15, 108, CWidth - 30, 32)];
    _itemScroll.showsVerticalScrollIndicator = NO;
    _itemScroll.showsHorizontalScrollIndicator = NO;
    _itemScroll.alwaysBounceVertical = NO;
    [_bottomView addSubview:_itemScroll];
    
    UILabel *labDesc = [[UILabel alloc] initWithFrame:CGRectMake(15, 161, CWidth - 30, 24)];
    [labDesc setFont:FontThirteen];
    [labDesc setText:@"一次性 开通3个月 只需16元，立省2元！"];
    [labDesc setTextColor:UIColorFromRGB(TextSizeOneColor)];
    [_bottomView addSubview:labDesc];
    
    
    _labPrice = [[UILabel alloc] initWithFrame:CGRectMake(15, 194, ScreenWidth - 30, 24)];
    [_labPrice setFont:FontThirteen];
    [_labPrice setTextColor:UIColorFromRGB(TextSizeOneColor)];
    
    NSString *text = @"￥ 16 元";
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:text];
    [string addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(BgTitleColor) range:NSMakeRange(1, text.length - 2)];
    [_labPrice setAttributedText:string];
    [_bottomView addSubview:_labPrice];
    
    [self createButton];
    
    [self createCloseButton];
    
    [self loadVipList];
    
    
}

-(void)createButton{
    UIButton *btnClose = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnClose setFrame:CGRectMake(15, 228, CWidth - 30, 44)];
    [btnClose setTitle:@"确定" forState:0];
    [btnClose addTarget:self action:@selector(actionButton:) forControlEvents:UIControlEventTouchUpInside];
    [btnClose setBackgroundColor:UIColorFromRGB(BgTitleColor)];
    [btnClose setTitleColor:UIColorFromRGB(TextWhiteColor) forState:0];
    btnClose.layer.masksToBounds = YES;
    btnClose.layer.cornerRadius = 22.0f;
    [_bottomView addSubview:btnClose];
}


-(void)createCloseButton{
    UIButton *btnClose = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnClose setFrame:CGRectMake(CWidth - 30, 0, 30, 30)];
    [btnClose addTarget:self action:@selector(dissmisMenu) forControlEvents:UIControlEventTouchUpInside];
    [btnClose setBackgroundColor:UIColor.clearColor];
    [btnClose setImage:[UIImage imageNamed:@"发布 关闭 素材"] forState:0];
    btnClose.layer.masksToBounds = YES;
    btnClose.layer.cornerRadius = 22.0f;
    [_bottomView addSubview:btnClose];
}

-(void)loadVipList{
    [NetworkUtil POST:API_Getvipdetail parameters:@{@"session_uid":[UserUtil getUser].user_id} success:^(id responseObject, NSDictionary *dict) {
        _payInfo =  [[PayInfoEntity alloc] initWithDictionary:dict[@"data"]];
        CGFloat x = 0;
        for (int i=0; i<_payInfo.attr_list.count; i++) {
            VipTypeEntity *item = _payInfo.attr_list[i];
            x =   [self createShareButton:i+1 title:item f:x] + 10;
            
        }
        
        [_itemScroll setContentSize:CGSizeMake(x, 32)];
    } failure:^(NSError *error, NSString *message) {
        
    }];
}

-(CGFloat )createShareButton:(int) i title:(VipTypeEntity *) model f:(CGFloat) x{
    CGFloat y = 0;
    MyButton *btn = [MyButton buttonWithType:UIButtonTypeCustom];
    [btn setFrame:CGRectMake(x, y, 30, 50)];
    if([model.is_recommend intValue] == 1){
        [btn setTitle:[NSString stringWithFormat:@"%@ 推荐",model.name] forState:0];
        btn.selected = YES;
        checkBtn = btn;
    }else{
        [btn setTitle:[NSString stringWithFormat:@"%@",model.name] forState:0];
        btn.selected = NO;
    }
    btn.objTag = model;
    [btn setTitleColor:UIColorFromRGB(BgTitleColor) forState:UIControlStateSelected];
    [btn setTitleColor:UIColorFromRGB(0x262626) forState:UIControlStateNormal];
    [btn.imageView setContentMode:UIViewContentModeScaleAspectFit];
    [btn.titleLabel setFont:FontFiftent];
    [btn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
    [btn addTarget:self action:@selector(shareWithButton:) forControlEvents:UIControlEventTouchUpInside];
    btn.layer.borderColor = UIColorFromRGB(BgTitleColor).CGColor;
    btn.layer.borderWidth = 1.0f;
    btn.layer.cornerRadius = 4.0f;
    btn.layer.masksToBounds = YES;
    [_itemScroll addSubview:btn];
    btn.tag = i-1;
    CGSize s = [self autoWidthOfLabel:btn.titleLabel with:50];
    [btn setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
    [btn setFrame:CGRectMake(x, 0, s.width + 15, 32)];
    return CGRectGetMaxX(btn.frame);
}

/**
 计算Label高度
 
 @param label 要计算的label，设置了值
 @param width label的最大宽度
 */
- (CGSize )autoWidthOfLabel:(UILabel *)label with:(CGFloat )height{
    //Calculate the expected size based on the font and linebreak mode of your label
    // FLT_MAX here simply means no constraint in height
    CGSize maximumLabelSize = CGSizeMake(FLT_MAX, height);
    
    CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];
    
    //adjust the label the the new height.
//    CGRect newFrame = label.frame;
//    newFrame.size.width = expectedLabelSize.width;
//    label.frame = newFrame;
//    [label updateConstraintsIfNeeded];
    
    return expectedLabelSize;
}

-(void)shareWithButton:(MyButton *) shareButton{
    if(checkBtn){
        checkBtn.selected = NO;
    }
    shareButton.selected = YES;
    checkBtn = shareButton;
    
    VipTypeEntity *entity = checkBtn.objTag;
    
    NSString *text = [NSString stringWithFormat:@"￥ %@ 元",entity.price];
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:text];
    [string addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(BgTitleColor) range:NSMakeRange(1, text.length - 2)];
    [_labPrice setAttributedText:string];
}


-(void)actionButton:(UIButton *) btn{
    if(checkBtn != nil){
        VipTypeEntity *vip = checkBtn.objTag;
        _payInfo.checkType = vip;
    }
    ZZPayTypeView *pview = [[ZZPayTypeView alloc] initWithShareType:_curVC result:^(int code, NSDictionary *msg) {
        if(code == 0){
            [self dissmisMenu];
        }
        _VipPayResult(code,msg);
    }];
    pview.pageInfo = _payInfo;
    [pview show];
}


- (void)dissmisMenu{
    CGRect sheetViewF = self.frame;
    sheetViewF.origin.y = SCREEN_HEIGHT;
    self.backgroundColor = UIColor.clearColor;
    
    [UIView animateWithDuration:0.2 animations:^{
        
        self.alpha = 0.0;
        self.frame = sheetViewF;
        
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

-(void)show{
    DLog(@"--------展示");
    CGRect sheetViewF = self.frame;
    sheetViewF.origin.y = 0;
    self.frame = sheetViewF;
    
    CGRect bf = _bottomView.frame;
    bf.origin.y = ScreenHeight/2 - CHeight/2;
    [UIView animateWithDuration:0.3 animations:^{
        _bottomView.frame = bf;
        self.backgroundColor = UIColorFromRGBAlpha(TextBlackColor, 0.4);
    } completion:^(BOOL finished) {
        
    }];
}

@end
